import { Component } from '@angular/core';
import {ActionSheetController, Events, IonicPage, NavController, NavParams, ViewController} from 'ionic-angular';
import {AppService} from "../../../services/app.service";
import {MessageService} from "../../../services/message.service";

/**
 * Generated class for the MessageListPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-message-list',
  templateUrl: 'message-list.html',
})
export class MessageListPage {

  ctrl: string = 'AppDemoUserCtrl_list';

  hasmore = true;
  items = [];

  pageParam = {
    pageNum:1,
    rows:10,
  };

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public viewCtrl: ViewController,
              private messageService:MessageService,
              private appService:AppService,
              private actionSheetCtrl:ActionSheetController,
              private events:Events) {
  }

  ionViewDidLoad() {
    this.getItems();
    console.log('ionViewDidLoad MessageListPage');
  }

  getItems(){
    this.messageService.getMsgList().then(res=>{
      console.log(res);
      //将返回的结果集遍历放入items数组中
      for(var i=0; i<res.rows.length; i++){
        this.items.push(res.rows.item(i));
      }
      //this.items = res.rows;
      this.pageParam.pageNum += 1;
    })
  }

  /**
   * 上拉加载
   * @param infiniteScroll
   */
  doInfinite(infiniteScroll) {
    if (this.hasmore == false) {
      infiniteScroll.complete();
      return;
    }

    this.messageService.getMsgList(this.pageParam).then(res=>{
      if(res.rows.length>0){
        for(var i=0; i<res.rows.length; i++){
          this.items.push(res.rows.item(i));
        }
        this.pageParam.pageNum += 1;
      }else {
        this.hasmore = false;
        console.log("没有数据啦！")
      }
      infiniteScroll.complete();
    })

/*    this.appService.httpPost(this.ctrl,this.postData,this.pageParam,data =>{
      if(data[0].trs.length > 0) {
        //this.users = data[0].trs;
        this.items = this.items.concat(data[0].trs);
        this.pageParam.pageNum += 1;
      } else {
        this.hasmore = false;
        console.log("没有数据啦！")
      }
      infiniteScroll.complete();
    })*/
  }

  /**
   * 下拉刷新
   * @param refresher
   */
  doRefresh(refresher) {
    console.log('Begin async operation', refresher);
    //先同步，然后整个列表刷新
    this.messageService.syncMsg(()=>{
      //将列表清空且页数重置为1
      this.pageParam.pageNum = 1;
      this.items = [];
      this.getItems();
      console.log('Async operation has ended');
      refresher.complete();
    });
/*    setTimeout(() => {
      console.log('Async operation has ended');
      refresher.complete();
    }, 2000);*/
  }

  /**
   * 跳转消息详细页面
   * @param item
   */
  goDetails(item) {
    console.debug('go details:' + item);
    //将消息标记为已读
    this.tagAsRead(item);
    this.navCtrl.push('MessageDetailPage', { item: item });
  }


  dismiss() {
    this.viewCtrl.dismiss();
  }

  /**
   * 长按
   * @param event
   */
  pressEvent(event,item){
    this.showActionSheet(item);
  }


  //选择
  showActionSheet(item) {
    if(item.state == '1'){
      var buttons = [
        {
          text: '删除',
          handler: ()=> {
            this.appService.confirm('是否确认删除',()=>{
              this.delMsg(item);
            })
          }
        },
        {
          text: '取消',
          role: 'cancel',
          handler: ()=> {
          }
        }
      ]
    } else if(item.state == '0'){
      buttons = [
        {
          text: '标记为已读',
          handler: ()=> {
            this.tagAsRead(item);
          }
        },
        {
          text: '删除',
          handler: ()=> {
            this.appService.confirm('是否确认删除',()=>{
              this.delMsg(item);
            })
          }
        },
        {
          text: '取消',
          role: 'cancel',
          handler: ()=> {
          }
        }
      ]
    }
    let actionSheet=
      this.actionSheetCtrl.create({
        title: '请选择',
        buttons: buttons
      });
    actionSheet.present();
  }

  /**
   * 标记为已读
   * @param item
   */
  tagAsRead(item){
    item.state = '1';
    this.messageService.updateMsgStatus(item);
    this.events.publish('updateMsgCount');
  }

  /**
   * 删除消息
   * @param item
   */
  delMsg(item){
    this.items.splice(this.items.indexOf(item),1);
    this.messageService.delMsg(item);
    this.events.publish('updateMsgCount');
  }
}
